package com.spsoft.vatoutinv.service.nvatoutinvoice.impl;

import cn.hutool.core.date.DateUtil;
import com.spsoft.core.model.Result;
import com.spsoft.core.utils.StringUtil;
import com.spsoft.system.entity.NvatOutInvoiceDetails;
import com.spsoft.system.entity.NvatOutInvoiceItems;
import com.spsoft.system.mapper.NvatOutInvoiceDetailsMapper;
import com.spsoft.system.mapper.NvatOutInvoiceItemsMapper;
import com.spsoft.system.model.vo.InvoiceVo;
import com.spsoft.system.service.SequenceService;
import com.spsoft.vatoutinv.constants.CommonConstant;
import com.spsoft.vatoutinv.entity.vmsfulloutinvoice.VmsFullOutInvoiceDetails;
import com.spsoft.vatoutinv.entity.vmsfulloutinvoice.VmsFullOutInvoiceItems;
import com.spsoft.vatoutinv.enums.ChyyEnum;
import com.spsoft.vatoutinv.enums.CommonEnum;
import com.spsoft.vatoutinv.enums.FpztEnum;
import com.spsoft.vatoutinv.mapper.VatNvatOutInvoiceDetailsMapper;
import com.spsoft.vatoutinv.mapper.VmsFullOutInvoiceDetailsMapper;
import com.spsoft.vatoutinv.model.vo.transflowfindinvoice.TransFlowRecallInvoiceInfoVO;
import com.spsoft.vatoutinv.service.nvatoutinvoice.NvatOutInvoiceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 老增值税系统接口服务实现类
 *
 * @author : chenxudong
 * @date : 2023/12/14 16:49
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NvatOutInvoiceServiceImpl implements NvatOutInvoiceService {

    private final NvatOutInvoiceDetailsMapper nvatOutInvoiceDetailsMapper;

    private final NvatOutInvoiceItemsMapper nvatOutInvoiceItemsMapper;

    private final VatNvatOutInvoiceDetailsMapper vatNvatOutInvoiceDetailsMapper;

    private final SequenceService sequenceService;

    private final VmsFullOutInvoiceDetailsMapper vmsFullOutInvoiceDetailsMapper;
    @Override
    public Long insertNvatOutInvoiceDetails(VmsFullOutInvoiceDetails vmsDetails, String deptCode, String fpdm) {
        NvatOutInvoiceDetails nvatDetails = new NvatOutInvoiceDetails();

        // 获取老系统发票主信息表主键序列
        Long oidId = sequenceService.getSequence(CommonConstant.TABLE_NVAT_OUTINVOICEDETAILS);
        nvatDetails.setOidid(oidId);
        nvatDetails.setFplxdm(vmsDetails.getFppz());
        nvatDetails.setSffsfp(vmsDetails.getLzfpbz());
        nvatDetails.setFpqqlsh(StringUtils.leftPad(StringUtil.toString(oidId), 50, "0"));
        nvatDetails.setTspz(CommonConstant.STR_00);
        nvatDetails.setSfqdkp(0);
        nvatDetails.setFphm(vmsDetails.getFphm());
        nvatDetails.setFpdm(fpdm);
        nvatDetails.setKprq(vmsDetails.getKprq());
        nvatDetails.setKpsq(DateUtil.format(vmsDetails.getKprq(), CommonConstant.DATE_FORMAT_5));
        nvatDetails.setSpfmc(vmsDetails.getGmfmc());
        nvatDetails.setSpfsbh(vmsDetails.getGmfnsrsbh());
        nvatDetails.setHjje(vmsDetails.getHjje());
        nvatDetails.setHjse(vmsDetails.getHjse());
        nvatDetails.setJshj(vmsDetails.getJshj());
        if (StringUtils.isNotBlank(vmsDetails.getBz()) && vmsDetails.getBz().length() > 128) {
            nvatDetails.setKpbz(vmsDetails.getBz().substring(0, 128));
        } else {
            nvatDetails.setKpbz(vmsDetails.getBz());
        }
        // 获取开票单位id
        String sbdwId = nvatOutInvoiceDetailsMapper.getSbdwId(deptCode);
        nvatDetails.setSbdwid(sbdwId);
        nvatDetails.setKpdw(vmsDetails.getXsfmc());
        nvatDetails.setKpnsrsbh(vmsDetails.getXsfnsrsbh());
        nvatDetails.setKpry(vmsDetails.getKpr());
        nvatDetails.setXxbbm(vmsDetails.getHzqrxxdbh());
        nvatDetails.setYfphm(vmsDetails.getDylzfphm());
        nvatDetails.setKpzt(2);
        nvatDetails.setQydjid(vmsDetails.getQydjid());
        nvatDetails.setFpmj(CommonConstant.STR_2);
        nvatDetails.setZfchrq(vmsDetails.getZfchrq());
        nvatDetails.setZfchyy(ChyyEnum.getValueByKey(vmsDetails.getZfchyy()));
        // 发票状态
        int fpzt = 0;
        if (StringUtils.isBlank(vmsDetails.getFpzt())
                || CommonEnum.INVOICE_STATUS_0.getKey().equals(vmsDetails.getFpzt())) {
            fpzt = 1;
        } else if (CommonEnum.INVOICE_STATUS_2.getKey().equals(vmsDetails.getFpzt())) {
            fpzt = 2;
        } else if (CommonEnum.INVOICE_STATUS_3.getKey().equals(vmsDetails.getFpzt())
                || CommonEnum.INVOICE_STATUS_7.getKey().equals(vmsDetails.getFpzt())
                || CommonEnum.INVOICE_STATUS_8.getKey().equals(vmsDetails.getFpzt())) {
            fpzt = 3;
        }
        nvatDetails.setFpzt(fpzt);
        nvatDetails.setSjly(Integer.parseInt(vmsDetails.getSjly()));
        nvatDetails.setExpcol3(vmsDetails.getSfbdc());
        nvatDetails.setPpzt(vmsDetails.getPpzt());
        nvatDetails.setFpzl(vmsDetails.getFppz());
        nvatDetails.setZsfs(StringUtils.isBlank(vmsDetails.getZsfs()) ? 0 : Integer.parseInt(vmsDetails.getZsfs()));
        nvatDetails.setYwdhlx(StringUtils.isBlank(vmsDetails.getDhlx()) ? "" : vmsDetails.getDhlx().substring(1));
        nvatDetails.setYwdh(vmsDetails.getDh());
        nvatOutInvoiceDetailsMapper.insert(nvatDetails);
        return nvatDetails.getOidid();
    }

    @Override
    public Long insertNvatOutInvoiceItems(VmsFullOutInvoiceItems vmsItems, Long oidId) {
        NvatOutInvoiceItems nvatItems = new NvatOutInvoiceItems();

        // 获取老系统发票明细信息表主键序列
        Long iviId = sequenceService.getSequence(CommonConstant.TABLE_NVAT_OUTINVOICEITEMS);
        nvatItems.setIviid(iviId);
        nvatItems.setCpbm(vmsItems.getCpbm());
        nvatItems.setSpmc(vmsItems.getXmmc());
        nvatItems.setGgxh(vmsItems.getGgxh());
        nvatItems.setJldw(vmsItems.getDw());
        nvatItems.setHsdj(formatStringToBigDecimal(vmsItems.getHsdj(), 14, 6));
        nvatItems.setDj(formatStringToBigDecimal(vmsItems.getDj(), 14, 6));
        nvatItems.setGmsl(formatStringToBigDecimal(vmsItems.getSl(), 14, 6));
        nvatItems.setJe(vmsItems.getJe());
        nvatItems.setSl(vmsItems.getSlv());
        nvatItems.setSe(vmsItems.getSe());
        nvatItems.setHsje(vmsItems.getJe().add(vmsItems.getSe()));
        nvatItems.setJsff(vmsItems.getJsff());
        nvatItems.setZsxm(vmsItems.getZsxm());
        nvatItems.setFphxz(vmsItems.getFphxz().substring(1));
        nvatItems.setOidid(oidId);
        nvatItems.setSpbm(vmsItems.getSphfwssflhbbm());
        nvatItems.setYhzcbs(StringUtils.isBlank(vmsItems.getYhzcbs()) ? 0 : 1);

        nvatOutInvoiceItemsMapper.insert(nvatItems);
        return nvatItems.getIviid();
    }

    @Override
    public int deleteNvatOutInvoiceDetails(Long oidId) {
        return nvatOutInvoiceDetailsMapper.deleteById(oidId);
    }

    @Override
    public int deleteNvatOutInvoiceItems(Long iviId) {
        return nvatOutInvoiceItemsMapper.deleteById(iviId);
    }

    @Override
    public Result<List<TransFlowRecallInvoiceInfoVO>> queryInvoiceByRdid(Integer rdid) {
        List<TransFlowRecallInvoiceInfoVO> result = new ArrayList<>();
        TransFlowRecallInvoiceInfoVO vo = vatNvatOutInvoiceDetailsMapper.queryInvoiceByRdid(rdid);
        if (vo == null) {
            return Result.OK(result);
        }
        if (vo.getFpzt() == null || vo.getFpzt().equals("1") || vo.getFpzt().equals("4")) {
            vo.setFpzt(FpztEnum.NORMAL.getKey());
        } else if ((vo.getFplxdm().equals(CommonEnum.INVOICE_TYPE_01.getKey()) || vo.getFplxdm().equals(CommonEnum.INVOICE_TYPE_02.getKey()))
                && vo.getFpzt().equals(FpztEnum.RED_FLUSH.getKey())) {
            // 查询数电票的发票状态
            InvoiceVo invoiceVo = vmsFullOutInvoiceDetailsMapper.queryInvoice(vo.getFphm(), null);//.getOne(new LambdaQueryWrapper<VmsFullOutInvoiceDetails>()
            if (invoiceVo != null) {
                vo.setFpzt(invoiceVo.getSdfpzt());
            }
        }
        result.add(vo);
        return Result.OK(result);
    }

    /**
     * 将String转为BigDecimal
     * @param string 待转换的字符串
     * @param maxInteger BigDecimal的最大整数位
     * @param maxDecimal BigDecimal的最大小数位
     */
    private BigDecimal formatStringToBigDecimal(String string, int maxInteger, int maxDecimal) {
        if (StringUtils.isBlank(string)) {
            return null;
        }
        BigDecimal bigDecimal = new BigDecimal(string).setScale(maxDecimal, RoundingMode.HALF_UP);
        // 去掉尾部多余的0
        bigDecimal = bigDecimal.stripTrailingZeros();
        // 获取参数的整数位数
        int integerDigits = bigDecimal.precision() - bigDecimal.scale();
        if (integerDigits > maxInteger) {
            // 整数位大于数据库字段限制的最大整数位
            return null;
        } else {
            return bigDecimal;
        }
    }
}
